﻿using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;

namespace EasyXaf.Blazor.ColorPickers;

public partial class ColorPalatteRenderer : IAsyncDisposable
{
    private ElementReference ContainerElementRef { get; set; }

    private DotNetObjectReference<ColorPalatteRenderer> DotNetObjectRef { get; set; }

    private IJSObjectReference JsModule { get; set; }

    [Parameter]
    public string Color { get; set; }

    [Parameter]
    public EventCallback<string> ColorChanged { get; set; }

    [Inject]
    public IJSRuntime JSRuntime { get; set; }

    [JSInvokable]
    public async Task SetColorAsync(string color)
    {
        if (Color != color)
        {
            await ColorChanged.InvokeAsync(color);
        }
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);

        if (firstRender)
        {
            var jsModuleFile = "./_content/EasyXaf.Blazor.ColorPickers/ColorPalatteRenderer.razor.js";
            JsModule = await JSRuntime.InvokeAsync<IJSObjectReference>("import", jsModuleFile);
            DotNetObjectRef = DotNetObjectReference.Create(this);
            await JsModule.InvokeVoidAsync("init", ContainerElementRef, DotNetObjectRef, Color);
        }
    }

    public async ValueTask DisposeAsync()
    {
        try
        {
            if (JsModule != null)
            {
                await JsModule.InvokeVoidAsync("dispose", ContainerElementRef);
            }
        }
        catch (JSDisconnectedException)
        {
        }

        if (JsModule != null)
        {
            await JsModule.DisposeAsync();
            JsModule = null;
        }

        DotNetObjectRef?.Dispose();
        DotNetObjectRef = null;

        GC.SuppressFinalize(this);
    }
}